<?php
/**
 * class with static utility functions
 */   
class Tools
{
  /**
   *utf to ascii equivalent conversion
   *
   *@param string $utf8_string
   *@return string $ascii_string
   */              
  static public function utf2ascii($utf8_string)
  { 
   $ascii_string= strtr(utf8_decode($utf8_string),utf8_decode("ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ"),"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"); 
   return $ascii_string; 
  }
  /**
   * A recursive glob function.
   * @param string $sDir directory to scan recursively
   * @param string $sPattern pattern to match
   * @param array $nFlags glob flags         
   * @return array
   */      
  static public function globr($sDir, $sPattern, $nFlags = NULL)
  {
    if(substr($sDir,-1,1)=='/') // remove trailing dir slash
    {
      $sDir = substr($sDir,0,-1);
    }
    $sDir = escapeshellcmd($sDir);
    $aFiles = glob("$sDir/$sPattern", $nFlags);
    foreach (glob("$sDir/*", GLOB_ONLYDIR) as $sSubDir)
    {
      $aSubFiles = self::globr($sSubDir, $sPattern, $nFlags);
      $aFiles = array_merge($aFiles, $aSubFiles);
    }
    return $aFiles;
  }
  /**
   * Enforce the use of ascii alphanum lowercase
   * 
   * Useful to create clean file and path name      
   * 
   * @param string $string string to convert
   * @return string           
   */  
  static public function cleanFileName($string)
  {
   $string = mb_strtolower($string);
   $string = self::utf2ascii($string);
   $string=ereg_replace("[^a-z0-9._-]","_",$string);
   return($string);
  }
  /**
   * Test if given string is an email
   * 
   * Useless now with php filters      
   *    
   * @param string $email
   * @return boolean
   */           
  static public function isMail($email)
  {
    if (preg_match("!^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$!", $email))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  /**
   * print information about given data
   *    
   * Prints colored var_dump
   *    
   * @param mixed any kind of data (arrays, strings, object, whatever...)
   */     
  static public function print_rn($data)
  {
    ob_start();
    var_dump($data);
    $c = ob_get_contents();
    ob_end_clean();
 
    $c = preg_replace("/\r\n|\r/", "\n", $c);
    $c = str_replace("]=>\n", '] = ', $c);
    $c = preg_replace('/= {2,}/', '= ', $c);
    $c = preg_replace("/\[\"(.*?)\"\] = /i", "[$1] = ", $c);
    $c = preg_replace('/    /', "        ", $c);
    $c = preg_replace("/\"\"(.*?)\"/i", "\"$1\"", $c);
 
    $c = htmlspecialchars($c, ENT_NOQUOTES);
 
    // Expand numbers (ie. int(2) 10 => int(1) 2 10, float(6) 128.64 => float(1) 6 128.64 etc.)
    $c = preg_replace("/(int|float)\(([0-9\.]+)\)/ie", "'$1('.strlen('$2').') <span class=\"number\">$2</span>'", $c);
    
    // Syntax Highlighting of Strings. This seems cryptic, but it will also allow non-terminated strings to get parsed.
    $c = preg_replace("/(\[[\w ]+\] = string\([0-9]+\) )\"(.*?)/sim", "$1<span class=\"string\">\"", $c);
    $c = preg_replace("/(\"\n{1,})( {0,}\})/sim", "$1</span>$2", $c);
    $c = preg_replace("/(\"\n{1,})( {0,}\[)/sim", "$1</span>$2", $c);
    $c = preg_replace("/(string\([0-9]+\) )\"(.*?)\"\n/sim", "$1<span class=\"string\">\"$2\"</span>\n", $c);
    
    $regex = array(
            // Numberrs
            'numbers' => array('/(^|] = )(array|float|int|string|resource|object\(.*\)|\&amp;object\(.*\))\(([0-9\.]+)\)/i', '$1$2(<span class="number">$3</span>)'),
            
            // Keywords
            'null' => array('/(^|] = )(null)/i', '$1<span class="keyword">$2</span>'),
            'bool' => array('/(bool)\((true|false)\)/i', '$1(<span class="keyword">$2</span>)'),
            
            // Types
            'types' => array('/(of type )\((.*)\)/i', '$1(<span class="type">$2</span>)'),
            
            // Objects
            'object' => array('/(object|\&amp;object)\(([\w]+)\)/i', '$1(<span class="object">$2</span>)'),
            
            // Function
            'function' => array('/(^|] = )(array|string|int|float|bool|resource|object|\&amp;object)\(/i', '$1<span class="function">$2</span>('),
    );
    
    foreach ($regex as $x) {
            $c = preg_replace($x[0], $x[1], $c);
    }
    
    $style = '
    /* outside div - it will float and match the screen */
    .dumpr {
            margin: 2px;
            padding: 2px;
            background-color: #fbfbfb;
            float: left;
            clear: both;
    }
    /* font size and family */
    .dumpr pre {
            color: #000000;
            font-size: 9pt;
            font-family: "Courier New",Courier,Monaco,monospace;
            margin: 0px;
            padding-top: 5px;
            padding-bottom: 7px;
            padding-left: 9px;
            padding-right: 9px;
    }
    /* inside div */
    .dumpr div {
            background-color: #fcfcfc;
            border: 1px solid #d9d9d9;
            float: left;
            clear: both;
    }
    /* syntax highlighting */
    .dumpr span.string {color: #c40000;}
    .dumpr span.number {color: #ff0000;}
    .dumpr span.keyword {color: #007200;}
    .dumpr span.function {color: #0000c4;}
    .dumpr span.object {color: #ac00ac;}
    .dumpr span.type {color: #0072c4;} 
    .legenddumpr {
   		background-color: #fcfcfc;
        border: 1px solid #d9d9d9;
        padding: 2px;           
    }        
    ';
    
    $style = preg_replace("/ {2,}/", "", $style);
    $style = preg_replace("/\t|\r\n|\r|\n/", "", $style);
    $style = preg_replace("/\/\*.*?\*\//i", '', $style);
    $style = str_replace('}', '} ', $style);
    $style = str_replace(' {', '{', $style);
    $style = trim($style);
 
    $c = trim($c);
    $c = preg_replace("/\n<\/span>/", "</span>\n", $c);
    
    echo "<style type=\"text/css\">".$style."</style>\n";
	echo '<fieldset class="dumpr">';
		echo '<legend class="legenddumpr">'.basename($_SERVER['SCRIPT_FILENAME']).'</legend>';
		//echo '<div>';
			echo '<pre>'.$c.'</pre>';
		//echo '</div>';
		
	echo '</fieldset>';
    echo "<div style=\"clear:both;\">&nbsp;</div>";
}
  /**
  * prints various infos if debug mode enabled (i.e. APP_DEBUG to true)
  */ 
  static public function debugInfos()
  {
    if(APP_DEBUG)
    {
      echo('<pre style="margin:2em;padding:2em;background-color:white;border:2px solid red;">');
      if(!empty($_SESSION)){echo('<strong>--- SESSION:</strong><br/>');self::print_rn($_SESSION);}
      if(!empty($_POST)){echo('<strong>--- POST:</strong><br/>');self::print_rn($_POST);}
      if(!empty($_GET)){echo('<strong>--- GET:</strong><br/>');self::print_rn($_GET);}
      echo('<strong>--- FILES:</strong><br/>');self::print_rn($_FILES);
      echo('<strong>--- SERVER:</strong><br/>');self::print_rn($_SERVER);
      echo('</pre>');
    }
  }
  /**
   * remove magic quotes
   * 
   * removes slashes recursively on superglobal arrays.
   * 
   * @param array $_POST or $_GET
   */                 
  static public function remove_magic_quotes(&$array)
  {
    foreach($array as $key => $val)
    {
      if(is_array($val))
      {
        self::remove_magic_quotes($array[$key]);
      }
      else if(is_string($val))
      {
        $array[$key] = stripslashes($val);
      }
    }
  }
  /**
   * send message alert to application admin email.
   * 
   * @param string
   */   
  static public function adminAlert($msg)
  {
    $msgT = 'probleme sur '.APP_NAME;
    mail(ADMIN_MAIL,$msgT,$msg);
  }
  
  /**
   * Determine 2 letter lang code from browser
   */
   static public function getLang()
   {
    if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
    {
      $lang = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
      $lang = strtolower(substr(chop($lang[0]),0,2));
      return $lang;
    }
    else
    {
      return false;
    }
   }
   
   /**
    * php array to js object
    */       
   static public function conv_tabjs($tableau, $nomjs, $prempass=true)
   {
    if($prempass)
    {
      $taille = count($tableau);
      echo "var ".$nomjs." = new Object();\n";
      foreach($tableau as $key => $val)
      {
        if(is_string($key)) $key = "'".$key."'";
        self::conv_tabjs($val, $nomjs."[".$key."]", false);
      }
    }
    else
    {
      if(is_array($tableau))
      {
        echo($nomjs." = new Array(".count($tableau).");\n");
        foreach($tableau as $key => $val)
        {
          if(is_string($key)) $key = "'".$key."'";
          self::conv_tabjs($val, $nomjs."[".$key."]", false);
        }
      }
      else
      {
        if(is_string($tableau)) $tableau = "'".addcslashes(ucfirst($tableau),"'")."'";
        echo($nomjs." = ".$tableau.";\n");
      }
    }
  }      
  
  /**
   *Rename workaround for winxp
   */
   public static function rename_win($oldfile,$newfile)
   {
    if(!rename($oldfile,$newfile))
    {
      if (copy($oldfile,$newfile))
      {
        unlink($oldfile);
        return true;
      }
      return false;
    }
   return true;
  }     

  /**
   *Curl copy
   */
  public static function curl_cp($src,$dst)
  {
    if(USE_PROXY)
    {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_PROXY, PROXY_URL);
      curl_setopt($curl,CURLOPT_URL,$src);
      curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
      return(file_put_contents($dst,curl_exec($curl)));
    }
    return(copy($src,$dst));
  }

  /**
   *Curl getContent
   */
  public static function curl_content($src)
  {
    if(USE_PROXY)
    {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_PROXY, PROXY_URL);
      curl_setopt($curl,CURLOPT_URL,$src);
      curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
      return(curl_exec($curl));
    }
    return(file_get_contents($src));
  }

}
?>
